package com.f21.f21assessoria.model.Operadores;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;

import org.hibernate.type.BigDecimalType;

public class ComparadorGenerico implements  Serializable {
	private static final long serialVersionUID = 1L;
	private String metodo;
	private String classe;
	final int BEFORE = -1;
	final int EQUAL = 0;
	final int AFTER = 1;

	public ComparadorGenerico(Class c, String metodo) {
		this.classe = c.getName();
		this.metodo=metodo;
	}

	public ComparadorGenerico(Object obj, String metodo) {
		this.classe = obj.getClass().getName();
		this.metodo=metodo;
	}
	
	public ComparadorGenerico(String classe, String metodo) {
		this.classe = classe;
		this.metodo=metodo;
	}

	public int comparar(Object atual, Object o) {

		try {
			if (getMetodo().getGenericReturnType() == String.class) {
				return compararString(atual, o);
			} else 
				return comparadorLong(atual, o);
			
			
		} catch (NoSuchMethodException | SecurityException
				| ClassNotFoundException |IllegalAccessException |IllegalArgumentException |InvocationTargetException e) {
			e.printStackTrace();
			return 0;
		}
	}

	public int compararBigDecimal(Object atual, Object o)
			throws IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
		BigDecimal obj = (BigDecimal) getMetodo().invoke(atual, null);
		BigDecimal obj2 = (BigDecimal) getMetodo().invoke(o, null);

		return obj.compareTo(obj2);
	}

	public int compararString(Object atual, Object o)
			throws IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
		String obj = (String) getMetodo().invoke(atual, null);
		String obj2 = (String) getMetodo().invoke(o, null);
		return obj.compareTo(obj2);
	}
	
	public int comparadorLong(Object atual, Object o)throws IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
		int obj = (int) getMetodo().invoke(atual, null);
		int obj2 = (int) getMetodo().invoke(o, null);
		
		 if(obj < obj2 ) return BEFORE;
		    if(obj >obj2) return AFTER;
		    return EQUAL;
	}


	private Method getMetodo() throws NoSuchMethodException, SecurityException,
			ClassNotFoundException {
		Method m = Class.forName(classe).getMethod(metodo, null);
		return Class.forName(classe).getMethod(metodo, null);
	}

}
